<template>
    <div class="create-post-page">
        <h4>新建文章</h4>
        <Uploader action="/upload" 
        :beforeUpload="uploadCheck" 
        @file-uploaded="handleFileUploaded" 
        @file-uploaded-error="onFileUploadedError"
        class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
        >
        <h2>点击上传头图</h2>
            <!-- 使用插槽，将Loading的效果嵌套到子组件中 -->
            <template #loading>
                <div class="d-flex">
                    <div class="spinner-border text-secondary" role="status">
                        <span class="sr-only"></span>
                    </div>
                    <h2>正在上传</h2>
                </div>
            </template>
            <!-- 使用插槽，将该内容嵌套到子组件中 -->
            <template #success="dataProps">
               <img :src="dataProps.uploadedData.data.url" width="500">
            </template>
        </Uploader>
        <validate-form @form-submit="onFormSubmit">
            <div class="mb-3">
                <label class="form-label">文章标题：</label>
                <ValidateInput :rules="titleRules" v-model="titleVal" placeholder="请输入文章标题" type="text" tag="input"></ValidateInput>
            </div>
            <div class="mb-3">
                <label class="form-label">文章详情：</label>
                <ValidateInput :rules="DetailRules" v-model="contentVal" placeholder="请输入文章详情" type="text" tag="textarea"></ValidateInput>
            </div>
            <template #submit>
                <button class="btn btn-primary btn-large">发表文章</button>
            </template>
        </validate-form>
    </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import ValidateInput from '@/components/ValidateInput.vue';
import ValidateForm from '@/components/ValidateForm.vue';
import { RulesProp,PostProps,ResponseType,ImageProps} from '@/utlis/type';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import Uploader from '@/components/Uploader.vue';
import createMessage from '@/components/createMessage';
import beforeUploadedCheck from '@/utlis/helper';
const router = useRouter()
const store = useStore()
const titleVal = ref('')
const contentVal = ref('')
let imageId = ''
const titleRules :RulesProp = [
    {type:'required',message:'文章标题不能为空！'}
]
const DetailRules : RulesProp = [
    {type:'required',message:'文章内容不能为空！'}
]
//新建文章，将文章信息插入数据库
const onFormSubmit = (result:boolean) =>{
   if(result){
    const {column,_id} = store.state.user
    if(column){
        const newPost:PostProps = {
            title:titleVal.value,
            content:contentVal.value,
            column,
            author:_id
        }
        if(imageId){
            newPost.image = imageId
        }
        store.dispatch('createPost',newPost).then(()=>{
            createMessage('发表成功，2秒后跳转到文章','success')
            setTimeout(()=>{
                router.push({name:"column",params:{id:column}})
            },2000)
        })
       
    }
   }
}
//当获取失败的自定义事件
const  onFileUploadedError = () =>{
    createMessage('上传图片失败','error')
}
//验证上传时进行文件格式和文件大小的检查
const uploadCheck = (file:File) =>{
    const result = beforeUploadedCheck(file,{format:['image/jpeg','image/png'],size:1})
    const {passed,error} = result
    if(error == 'format'){
        createMessage('上传的图片只能是JPG/PNG格式！','error')
    } else if(error == 'size'){
        createMessage('上传图片的大小不能超过1MB','error')
    }
    return passed
} 
//发起异步的请求
const handleFileUploaded = (rawData:ResponseType<ImageProps>) =>{
    createMessage('上传图片成功！','success')
    if(rawData.data._id){
        imageId = rawData.data._id
    }
}
</script>
<style>
.create-post-page .file-upload-container{
    height: 200px;
    cursor: pointer;
}
.create-post-page .file-upload-container img{
    width: 100%;
    height: 100%;
    object-fit: cover;
}
</style>